package com.example.qt.ptplatform.service.impl;

import com.example.qt.ptplatform.entity.CommentImage;
import com.example.qt.ptplatform.mapper.CommentImageMapper;
import com.example.qt.ptplatform.service.CommentImageService;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;

@Service
public class CommentImageServiceImpl implements CommentImageService {

    @Autowired
    private CommentImageMapper commentImageMapper;

    @Override
    public boolean saveCommentImage(Long torrentId, Long userId, Integer commentId, MultipartFile imageFile) {
        try {
            // 将图片转换为Base64编码
            byte[] imageBytes = imageFile.getBytes();
            String imageBase64 = Base64.encodeBase64String(imageBytes);

            // 构建实体对象
            CommentImage commentImage = new CommentImage();
            commentImage.setTorrentId(torrentId);
            commentImage.setUserId(userId);
            commentImage.setCommentId(commentId); // 设置评论ID
            commentImage.setImageData(imageBase64);
            commentImage.setCreatedAt(LocalDateTime.now());

            // 保存到数据库
            return commentImageMapper.insert(commentImage) > 0;
        } catch (IOException e) {
            throw new RuntimeException("图片处理失败", e);
        }
    }
}